using UnityEngine;

public class MousePerson : MonoBehaviour {
CharacterController player;// Player
public float radiusNoClick = 3f;// Sensivity for move player to target
public Vector3 target = Vector3.zero;//Target position
private Vector3 direction;// Move direction vector
public float speedRotation = 10f;// Speed of rotation
public float speedMove = 45f;// Speed for walking
private bool onPlace = true;// Boolean flag for player to move
private Animation _animation;// Animation
// State of class
enum CharacterState {
Idle = 0,
Walking = 1,
}
private CharacterState _characterState;// State object

void Start() {
	// Get Animation
	_animation = GetComponent();
	// Get player
	player = (CharacterController)gameObject.GetComponent(typeof(CharacterController));
}

void Update() {
if (!onPlace) {
	// Calculate direction for movement
	direction = target - this.transform.position;
	// Vector normalization
	direction = new Vector3(direction.x, 0, direction.z);
	direction.Normalize();

	// ROtate player
	Quaternion look = Quaternion.LookRotation(direction);
	this.transform.rotation = Quaternion.Slerp(this.transform.rotation, look, Time.deltaTime * speedRotation);

	// move player
	player.Move(direction * Time.deltaTime * speedMove);

	// change state to walking
	_characterState = CharacterState.Walking;
}
else
	// Set player state to idle
	_characterState = CharacterState.Idle;

if (_animation) {
	// Switch for diferent animation
	if (_characterState == CharacterState.Walking)
	_animation.Play("walk", PlayMode.StopAll);
	else if (_characterState == CharacterState.Idle)
	_animation.Play("idle", PlayMode.StopAll);
}
}

public void GetTarget(Vector3 target) {
// Check Target position
if ((Mathf.Abs(transform.position.x - target.x) >= radiusNoClick) &&
(Mathf.Abs(transform.position.z - target.z) >= radiusNoClick))
{
	this.target = target;
	// call player to stop
	onPlace = false;
}
}

public void OnPlaceTrue() {
	onPlace = true;
}
}